package org.ling.xuan.action;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.ling.xuan.condition.LxCondition;
import org.ling.xuan.dao.FileDao;
import org.ling.xuan.dao.LocalAddDao;
import org.ling.xuan.dao.ProjectDao;
import org.ling.xuan.dialog.AddInfoDialog;
import org.ling.xuan.entity.HundSonInfo;
import org.ling.xuan.entity.mo.CommonSetting;
import org.ling.xuan.entity.mo.LocalAdd;
import org.ling.xuan.entity.mo.ProjectSetting;
import org.ling.xuan.util.LoggerUtil;
import org.ling.xuan.util.LxOptional;
import org.ling.xuan.util.LxStrUtil;

import java.util.Date;
import java.util.List;

/**
 * 自动生成版本修改信息,全文件递增版本号
 *
 * @author liting50684
 * @date 2023/08/21
 */
public class LxAnnotationGenerateAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        Editor editor = e.getDataContext().getData(com.intellij.openapi.actionSystem.PlatformDataKeys.EDITOR);
        LocalAdd localAdd = null;
        localAdd = LocalAddDao.getCur();
        if (StrUtil.isBlank(localAdd.getModifyId())) {
            AddInfoDialog addInfoDialog = new AddInfoDialog(e.getProject(), true, localAdd);
            if (addInfoDialog.showAndGet()) {
                localAdd = addInfoDialog.getSetting();
                if (StrUtil.isBlank(localAdd.getModifyId()) || StrUtil.isBlank(localAdd.getAddMsg())) {
                    LoggerUtil.log(e.getProject(), "未设置修改单号和修改消息,插入注释失败,请重新插入");
                    return;
                } else {
                    LocalAddDao.updateCurAddSimple(localAdd);
                    localAdd = LocalAddDao.getCur();
                }
            }
        }
        if (StrUtil.isNotBlank(localAdd.getModifyId()) || StrUtil.isNotBlank(localAdd.getAddMsg())) {
            String filePath = LxOptional.of(e, c -> c.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE).getPath()).orElse("");
            String basePath = LxOptional.of(e, c -> c.getProject().getBasePath()).orElse("");
            if (project != null && editor != null && StrUtil.isNotBlank(filePath)) {
                LxStrUtil.unionPath(filePath);
                LxStrUtil.unionPath(basePath);
                CommonSetting commonSetting = FileDao.get(CommonSetting.class, "CommonSetting.json", new CommonSetting());
                ProjectSetting projectSetting = ProjectDao.getSetting(basePath);
                HundSonInfo hundSonInfo = new HundSonInfo(filePath, projectSetting.getSystemName(), commonSetting.getAuth());
                String oldVersion = hundSonInfo.getLastAnnotationVersion();
                String version = oldVersion;
                if (StrUtil.isBlank(version) || StrUtil.isBlank(version)) {
                    version = "3.0.0.0";
                } else {
                    String[] arr = version.split("\\.");
                    if (arr.length > 1) {
                        int i = Integer.parseInt(arr[arr.length - 1]);
                        i++;
                        arr[arr.length - 1] = String.valueOf(i);
                        version = StrUtil.join(".", CollUtil.newArrayList(arr));
                    }
                }
                String order = "01";
                String la = StrUtil.format(" * V{}\t{}-{}\t{}\t\t{}\t{}", version, DateUtil.format(new Date(), "yyyyMMdd"),order, commonSetting.getAuth(), localAdd.getAddMsg(), localAdd.getModifyId());
                String ano = hundSonInfo.getAnnotationText();
                if (StrUtil.isNotBlank(ano)) {
                    String context = FileUtil.readUtf8String(filePath);
                    List<String> rr = StrUtil.split(ano, "\n");
                    if (rr.size() > 1) {
                        rr.add(rr.size() - 1, la);
                        String rt = StrUtil.join("\n", rr);
                        String ss = hundSonInfo.getMethodVersionText();
                        context = context.replace(ano, rt);
                        if (StrUtil.isNotBlank(ss)) {
                            context = context.replace(ss, ss.replace(hundSonInfo.getMethodVersion(), version));
                        }
                        String aa1 = hundSonInfo.getHundSonColText();
                        String aa = aa1;
                        if (StrUtil.isNotBlank(aa)) {
                            if (StrUtil.isNotBlank(hundSonInfo.getHundSonVersion())) {
                                aa = aa.replace(hundSonInfo.getHundSonVersion(), version);
                            }
                            if (StrUtil.isNotBlank(hundSonInfo.getHundSonDateText())) {
                                aa = aa.replace(hundSonInfo.getHundSonDateText(), "@lastModiDate\t" + DateUtil.format(new Date(), "yyyyMMdd")+" ");
                            }
                            if (StrUtil.isNotBlank(hundSonInfo.getHundSonDesText())) {
                                aa = aa.replace(hundSonInfo.getHundSonDesText(), "@describ\t" + hundSonInfo.getAuthSetting());
                            }
                            context = context.replace(aa1, aa);
                        }
                        write(project, editor, context);
                    }
                }
            }
        }
    }

    @Override
    public void update(AnActionEvent e) {
        boolean enable = LxCondition.getInstance().canAnnotationDeal(e);
        e.getPresentation().setEnabledAndVisible(enable);
    }

    private void write(Project project, Editor editor, String s) {
        if (project != null && editor != null) {
            WriteCommandAction.runWriteCommandAction(project, () -> {
                FileDocumentManager.getInstance().saveDocument(editor.getDocument());
                Document document = editor.getDocument();
                document.setText(s.replace("\r\n", "\n"));
                FileDocumentManager.getInstance().saveDocument(editor.getDocument());
            });
        }
    }
}
